<?php

class ScoreManager_ScoreStateController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        $this->view->yearSemester = $this->getRequest()->getPost('yearSemester');
        $this->view->selectGrade = $this->getRequest()->getPost('select-grade');
        if ( $this->view->yearSemester and $this->view->selectGrade) {
            $tempArr = explode("-",$this->view->yearSemester);
            $year = (int) $tempArr[0];
            $semester = (int)$tempArr[1];
            $grade = (int)$this->view->selectGrade;
            $examine = new Semester_Model_SemesterExamine();
            $examineSet = $examine->getExaminSet($year, $semester, $grade);
            // 考試設定
            $this->view->examineSet = $examineSet;

        }

        $stage = (int)$this->getRequest()->getPost('stage');
        if ($stage) {
            $this->view->stage = $stage;
            $semesterSubject = new Semester_Model_SemesterSubject();
            if ($stage==255)
            $scoreMode = Semester_Model_SemesterSubject::SCORE_MODE_WHOLE_SEMESTER;
            else
            $scoreMode = Semester_Model_SemesterSubject::SCORE_MODE_STAGE;
            // 年級科目
            $this->view->semesterSubject = $semesterSubject->getSubject($year, $semester,
            $grade,null,$scoreMode,'Y');

            // 年級班級數
            $semesterClass = new Semester_Model_SemesterClass();
            $this->view->className = $semesterClass->getGradeClassNames($year, $semester, $grade);

            // 查詢已傳送否
            $this->view->sendmitArr = $this->_getSendmit($year, $semester, $grade, $stage);

            // 本學期班級數
            $this->view->classStudentArr = $this->_getClassStudentArr($year, $semester,$grade);
        }
    }

    /**
     * 更改繳交狀況
     */
    public function setSendmitAction()
    {
        $id = (int) $this->_getParam('id');
        $q = Doctrine_Query::create()
        ->select('a.subject_sn, a.class_sn, a.test_sort, a.sendmit, b.year AS year, b.semester AS semester, b.grade AS grade')
        ->from('Student_Model_StudentScoreStage a')
        ->leftJoin('a.Semester_Model_SemesterSubject b')
        ->where('a.sn=?', $id);
        $res = $q->fetchOne();

        $q = Doctrine_Query::create()
        ->update('Student_Model_StudentScoreStage');
        if ($res->sendmit == 'Y')
        $q->set('sendmit','?', 'N');
        else
        $q->set('sendmit','?', 'Y');
        $q->where('subject_sn=?', $res->subject_sn)
        ->andWhere('class_sn=?', $res->class_sn)
        ->andWhere('test_sort=?', $res->test_sort);

        $q->execute();

        //  重算學期成績
        if ($res->sendmit == 'N') {
            $arr = array();
            // 全學期計算
            if ($res->test_sort == 255) {
                $q = Doctrine_Query::create()
                ->select('a.student_sn , a.score, b.test_kind AS test_kind')
                ->from ('Student_Model_StudentScoreStageDetail a')
                ->leftJoin('a.Student_Model_StudentScoreStage b')
                ->where('b.subject_sn=?',$res->subject_sn)
                ->andWhere('b.test_sort=?',$res->test_sort)
                ->andWhere('b.class_sn=?', $res->class_sn)
                ->groupBy('a.student_sn');
                $res2 = $q->fetchArray();

                foreach($res2 as $row) {
                    $arr[$row['student_sn']] = $row['score']  ;
                }
            }
            else {
                $examine = new Semester_Model_SemesterExamine();
                $ratioArr = $examine->getExaminSet($res->year, $res->semester, $res->grade);
                $ratio = $ratioArr->ratio;
                $q = Doctrine_Query::create()
                ->select('a.student_sn , a.score, b.test_kind AS test_kind, b.test_sort AS test_sort')
                ->from ('Student_Model_StudentScoreStageDetail a')
                ->leftJoin('a.Student_Model_StudentScoreStage b')
                ->where('b.subject_sn=?',$res->subject_sn)
                ->andWhere('b.class_sn=?', $res->class_sn)
                ->groupBy('a.student_sn, b.test_kind, b.test_sort');
                $res2 = $q->fetchArray();

                $totalRatio = 0;
                foreach($ratio as $val) {
                    if (is_array($val))
                    foreach($val as $vals)
                    $totalRatio += $vals;
                }

                // 比率計算
                foreach($res2 as $row) {
                    if(!isset($arr[$row['student_sn']]))
                    $arr[$row['student_sn']] = 0;
                    $arr[$row['student_sn']] += ($ratio[$row['test_sort']][$row['test_kind']] / $totalRatio) * $row['score'] ;
                }
            }

            // 填入學期成績
            if ($arr) {
                $teacherSn = Teacher_Model_Teacher::getSnById();
                foreach($arr as $studentSn=>$score) {
                    $studentScoreSemester =  new Student_Model_StudentScoreSemester() ;
                    $q = Doctrine_Query::create()
                    ->select('sn')
                    ->from('Student_Model_StudentScoreSemester')
                    ->where('student_sn=?', $studentSn )
                    ->andWhere('subject_sn=?', $res->subject_sn);
                    $sres = $q->fetchOne();
                    if ($sres)
                    $studentScoreSemester->assignIdentifier($sres->sn);
                    $studentScoreSemester->student_sn = $studentSn;
                    $studentScoreSemester->subject_sn = $res->subject_sn;
                    $studentScoreSemester->score = $score;
                    $studentScoreSemester->teacher_sn = $teacherSn;
                    $studentScoreSemester->save();
                }
            }

        }

        $q = Doctrine_Query::create()
        ->select('sn')
        ->from('Student_Model_StudentScoreStage')
        ->where('subject_sn=?', $res->subject_sn)
        ->andWhere('class_sn=?', $res->class_sn)
        ->andWhere('test_sort=?', $res->test_sort);

        $sres = $q->fetchArray();

        $this->_helper->json($sres);
    }

    /**
     * 圖檔連結
     */
    public function imageAction()
    {
        $photo = $this->_getParam('file');
        $fileName = dirname(__FILE__).'/../images/'.$photo;
        $this->_helper->Img($fileName);
    }

    /**
     * 班級學生人數
     * @param integer $year
     * @param integer $semester
     * @param integer $grade
     */
    protected function _getClassStudentArr($year, $semester, $grade)
    {
        $q = Doctrine_Query::create()
        ->select('COUNT(*) AS cc, class_sn')
        ->from('Student_Model_StudentSemester')
        ->where('year=?', $year)
        ->andWhere('semester=?', $semester)
        ->andWhere('grade=?', $grade)
        ->groupBy('class_sn');
        $arr = array();
        $res = $q->fetchArray();
        foreach($res as $row) {
            $arr[$grade.'-'.$row['class_sn']] = $row['cc'];
        }
        return $arr;

    }

    protected function _getSendmit($year, $semester, $grade, $testSort)
    {
        $q = Doctrine_Query::create()
        ->select('a.sn, a.sendmit, a.class_sn, a.subject_sn, a.test_kind')
        ->from('Student_Model_StudentScoreStage a')
        ->leftJoin('a.Semester_Model_SemesterSubject b')
        ->where('b.year=?', $year)
        ->andWhere('b.semester=?', $semester)
        ->andWhere('b.grade=?', $grade)
        ->andWhere('a.test_sort=?', $testSort);
        $res = $q->fetchArray();
        $arr = array();
        foreach ($res as $row) {
            $q = Doctrine_Query::create()
            ->select('COUNT(sn) AS cc')
            ->from('Student_Model_StudentScoreStageDetail')
            ->where('stage_sn=?', $row['sn']);
            $cres = $q->fetchOne();
            $arr[$grade.'-'.$row['class_sn']][$row['test_kind']][$row['subject_sn']] ['sn']= $row['sn'];
            $arr[$grade.'-'.$row['class_sn']][$row['test_kind']][$row['subject_sn']] ['sendmit']= $row['sendmit'];
            $arr[$grade.'-'.$row['class_sn']][$row['test_kind']][$row['subject_sn']] ['count']= $cres->cc;
        }
        return $arr;
    }


}

